import cookie from "./cookie";
import {Message} from 'element-ui'

import axios from "axios"
import config from "./config";


let baseURL = config.api.baseUrl;

let _axios = axios.create({
  baseURL: baseURL,
  headers: {
    "Content-Type": "application/json",
    "Accept": "application/json"
  },
  method: "post"
})

function request(url, data = {}, method = "POST", token = null) {


  let headers = {
    "Content-Type": "application/json",
    "Accept": "application/json"
  }

  //浏览器渲染
  if (process.browser) {
    //处理token
    let token = cookie.getCookie('token');
    if (token) {
      headers.token = token;
    }
  }

  if (token) {
    headers.token = token;
  }

  let config = {
    url: url,
    method: method,
    headers: headers
  }

  if (method === "POST") {
    config.data = data;
  } else {
    config.params = data;
  }

  return new Promise((resolve, reject) => {
    _axios.request(config).then(res => {
      //如果包含状态码 就提示，不包含就不处理
      let data = res.data;
      if (typeof (data.code) != "undefined") {
        // Message

        if (data.code !== 1) {
          //浏览器下才提示
          if (process.browser) {
            Message.error(data.msg);
          }
          reject(data.msg);
        } else {
          if (typeof (data.data) !== "undefined") {
            resolve(data.data);
          } else {
            resolve(data);
          }
        }
      } else {
        resolve(res.data);
      }
    }).catch(err => {
      console.error("请求地址：" + url);
      console.error(err);
      reject(err)
    });
  });
}

export default {
  baseUrl: baseURL,
  getCategory(data) {
    return request("/category");
  },
  getTopic(data) {
    return request("/topic", data)
  },
  getCarousel() {
    return request("/carousel")
  },
  getNavbar() {
    return request("/navbar")
  },
  getTopicById(id) {
    return request("/topic/id", {id})
  },
  /**
   * 帖子置顶
   * @param id
   * @returns {Promise<unknown>}
   */
  topicTop(id) {
    return request("/topic/top", {id});
  },
  /**
   * 帖子删除
   * @param id
   * @returns {Promise<unknown>}
   */
  topicDelete(id) {
    return request("/topic/delete", {id});
  },
  getIndexData() {
    return request("/index/data")
  },
  upload(file) {

    return new Promise((resolve, reject) => {
      let form = new FormData();
      form.append('file', file);

      //处理token

      _axios({
        url: '/upload',
        headers: {
          "Content-Type": "multipart/form-data",
          "Accept": "application/json"
        },
        data: form
      }).then(res => {
        resolve({url: res.data.url})
      }).catch(reject);
    });
  },
  search(q, page) {
    return request('/search', {q, page})
  },
  getComment(data) {
    //需要传入targetId和targetType
    return request('/comment/list', data)
  },
  getVerfCodeUrl(uid) {
    //获取验证码图片
    return `${baseURL}/verification/code?uid=${uid}`;
  },
  /**
   * 发送验证码短信
   * @param uid
   * @param code
   * @param phone
   */
  sendSmsCode(uid, code, phone) {
    return request('sms/code', {uid, code, phone});
  },
  /**
   * 短信验证码登录
   * @param phone
   * @param smsCode
   */
  smsLogin(phone, smsCode) {
    return request('sms/login', {phone, smsCode});
  },
  /**
   * 根据token获取用户
   * @param token
   */
  getUser(token) {
    return request('/user/info', {}, "POST", token);
  },
  /**
   * 通过用户id获取信息
   * @param userId
   * @returns {Promise<unknown>}
   */
  getUserDetail(userId) {
    return request('/user/detail', {userId});
  },
  /**
   * 退出登录
   * @param token
   * @returns {Promise<unknown>}
   */
  userLogout(token) {
    return request('/user/logout', {token});
  },
  /**
   * 保存评论
   * @param targetType
   * @param targetId
   * @param content
   * @param parentId
   * @param replyUserId
   */
  commentSave(targetType, targetId, content, parentId, replyUserId) {
    return request('/comment/post', {targetType, targetId, content, parentId, replyUserId});
  },
  /**
   * 删除评论
   * @param id
   */
  commentDelete(id) {
    return request('/comment/delete', {id});
  },
  /**
   * 评论点赞
   * @param id
   * @returns {Promise<unknown>}
   */
  commentUp(id) {
    return request('/comment/up', {id});
  },
  /**
   * 获取用户评论
   * @param userId
   * @param page
   * @returns {Promise<unknown>}
   */
  getUserComments(userId, page) {
    return request('/user/comments', {userId, page});
  },
  /**
   * 获取订单列表
   * @param userId
   * @param page
   * @returns {Promise<unknown>}
   */
  getOrders(userId, page) {
    return request('/order/list', {userId, page})
  },
  /**
   * 离线激活
   * @param deviceId
   * @param activeCode
   * @returns {Promise<unknown>}
   */
  orderOfflineActive(deviceId, activeCode) {
    return request('/order/offline/activate', {deviceId, activeCode})
  },
  /**
   * 设备绑定
   * @param deviceId
   * @returns {Promise<unknown>}
   */
  orderDeviceBind(deviceId) {
    return request('/order/device/bind', {deviceId})
  },
  /**
   * 激活记录下载
   * @param id
   * @returns {Promise<unknown>}
   */
  orderActiveHistoryDownload(id) {
    return request('/order/active/history/download', {id});
  },
  /**
   * 激活记录
   * @param activeId
   * @returns {Promise<unknown>}
   */
  activeHistoryList(activeId) {
    return request('/order/active/history/list', {activeId})
  },
  /**
   * 获取发票详情
   * @param orderId
   * @returns {Promise<unknown>}
   */
  getInvoiceDetail(orderId) {
    return request('/order/invoice/detail', {orderId})
  },
  /**
   * 发票申请
   * @param orderId
   * @param name
   * @param taxNo
   * @param phone
   * @returns {Promise<unknown>}
   */
  invoiceApply(data) {
    return request('/order/invoice/apply', data)
  },
  /**
   * 获取用户信息修改页的资料
   * @returns {Promise<unknown>}
   */
  getUserProfile() {
    return request('/user/profile')
  },
  /**
   * 个人资料保存
   * @param name
   * @param avatar
   * @param email
   * @returns {Promise<unknown>}
   */
  userProfileSave(data) {
    return request('/user/profile/save', data)
  },
  /**
   * 校验手机号是否存在
   * @param phone
   * @returns {Promise<unknown>}
   */
  userPhoneVerify(phone) {
    return request('/user/phone/verify', {phone});
  },
  /**
   * 修改手机号
   * @param phone
   * @param code
   * @returns {Promise<unknown>}
   */
  userPhoneModify(phone, code) {
    return request('/user/phone/modify', {phone, code});
  },
  /**
   * 发布帖子
   * @param id
   * @param title
   * @param content
   * @param nodeId
   * @param askUserId
   * @returns {Promise<unknown>}
   */
  postTopic(id, title, content, nodeId, askUserId) {
    return request('/post/topic', {id, title, content, nodeId, askUserId});
  },
  /**
   * 获取帖子编辑的数据
   * @param id
   */
  getTopicEditData(id) {
    return request('/topic/edit/data', {id});
  },
  /**
   * 获取套餐列表
   */
  getProPackage() {
    return request('/pro/package');
  },
  /**
   * 创建订单
   * @param packageId 套餐id
   * @param platform wx和alipay
   * @param discountCodeId 折扣码
   */
  orderCreate(packageId, platform, discountCodeId) {
    return request('/order/create', {packageId, platform, discountCodeId});
  },
  /**
   * 查询订单支付状态
   * @param orderNo
   */
  orderQuery(orderNo) {
    return request('order/query', {orderNo});
  },
  /**
   * 获取折扣码
   * @param code
   * @returns {Promise<unknown>}
   */
  getCoupon(code) {
    return request('/coupon/get', {code});
  },
  /**
   * 获取自定义页面
   * @param alias
   * @returns {Promise<unknown>}
   */
  getPage(alias) {
    return request('/page/get', {alias});
  },
  /**
   * 获取认证详情
   */
  getUserVerifyDetail() {
    return request('/user/verify/get');
  },
  /**
   * 用户认证申请
   * @param id
   * @param description
   * @param material
   * @returns {Promise<unknown>}
   */
  userVerifyApply(id, description, material) {
    return request('/user/verify/apply', {id, description, material});
  },
  /**
   * 取消认证
   * @returns {Promise<unknown>}
   */
  userVerifyCancel() {
    return request('/user/verify/cancel');
  },
  /**
   * 获取热门的话题
   * @returns {Promise<unknown>}
   */
  getTopicHot() {
    return request('/topic/hot');
  },
  /**
   * 获取没人回复的话题
   * @returns {Promise<unknown>}
   */
  getTopicNoAnswer() {
    return request('/topic/noAnswer');
  },
  /**
   * 获取推荐的用户
   * @returns {Promise<unknown>}
   */
  getUserRecommend() {
    return request('/user/recommend');
  },
  /**
   * 获取未读消息数量
   * @returns {Promise<unknown>}
   */
  getUserInvitationCount() {
    return request('/user/invitation/count');
  },
  /**
   * 获取被邀请回复问题列表
   * @returns {Promise<unknown>}
   */
  getUserInvitationList() {
    return request('/user/invitation/list');
  },
  /**
   * 邀请我回答的，设为已读
   * @returns {Promise<unknown>}
   */
  userInvitationReadall() {
    return request('/user/invitation/readall');
  },
  /**
   * 获取网站地图的url
   * @returns {Promise<unknown>}
   */
  getSitemapUrl() {
    return request('/sitemap/url');
  },
  /**
   * 加入/移除黑名单
   * @param userId
   * @returns {Promise<unknown>}
   */
  blacklist(userId) {
    return request('/user/blacklist', {userId});
  },
  /**
   * 获取活跃度榜单
   * @param limit
   * @returns {Promise<unknown>}
   */
  getUserActives(limit = 10) {
    return request('/user/actives', {limit});
  }
}

